package com.das.mechanic_base.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieCompositionFactory;
import com.airbnb.lottie.LottieTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.main.X3BottomHomeCarAndColorAdapter;
import com.das.mechanic_base.adapter.main.X3CarSexAdapter;
import com.das.mechanic_base.adapter.main.X3SelectSunNameAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseBottomCarSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.main.CarBrandAndCommonBean;
import com.das.mechanic_base.bean.main.CarBrandBean;
import com.das.mechanic_base.bean.main.CarModelSelectBean;
import com.das.mechanic_base.bean.main.CarNewTypeBean;
import com.das.mechanic_base.bean.main.CarNumRecognitionBean;
import com.das.mechanic_base.bean.main.CarPicAndColorBean;
import com.das.mechanic_base.bean.main.CarSelectBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.bean.main.UpdateReceiveCarBean;
import com.das.mechanic_base.bean.main.VinResultBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.ThreadPoolManager;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3ImgDownload;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3TimeUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.umeng.analytics.MobclickAgent;

import org.jetbrains.annotations.NotNull;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static android.view.View.GONE;

public class X3BottomAffirmCarDialog extends X3BaseBottomCarSheetDialog implements View.OnClickListener, TextWatcher, X3MemberButtonView.IOnClickAffirm, X3HomeTimeSelectDialog.IOnClickCar, X3CarSexAdapter.IOnClickSex, View.OnFocusChangeListener, ViewTreeObserver.OnGlobalLayoutListener, X3HomeChangeMileDialog.IonClickChangeMile {

    private LinearLayout ll_car_brand;
    private TextView tv_brand_name_span;
    private TextView et_car_brand;
    private ImageView iv_brand_icon;

    private LinearLayout ll_car_pic;
    private TextView tv_car_pic_span;
    private TextView tv_car_pic;
    private ImageView v_pic;
    private LottieAnimationView lv_car;

    private EditText et_car_last_name;

    private EditText et_car_name;

    private LinearLayout ll_time;
    private TextView tv_car_time_span;
    private TextView et_car_time;

    private LinearLayout ll_mile;
    private TextView tv_miles_span;
    private TextView et_miles;

    private EditText et_car_vin;
    private ImageView iv_take;

    private TextView tv_cancel;
    private X3MemberButtonView btn_next;

    private X3MyLinearLayout ll_use_name;
    private RecyclerView rlv_name;
    private RelativeLayout ll_use;
    private RecyclerView rlv_sex;

    private RelativeLayout ll_view;
    private View v_click;

    private TextView tv_title;

    private NestedScrollView nv_view;

    private long carBrandId,carStyleId,carTypeId,carId,colorId,carPicTempletId,allNum,cuteNum;

    private List<CarPicAndColorBean> mList;

    private HomeMainCarBean.CarPicTempletEntityBean picBean;
    private String carNum;
    private X3BottomHomeCarPicAndColorDialog picAndColorDialog;
    private Bitmap img_6;

    private boolean waitingForCarPicTemplet;
    private X3HomeBrandSelectDialog brandSelectDialog;

    private List<CarBrandBean> brandBeanList,carBrandList;
    private X3HomeStyleSelectDialog styleSelectDialog;
    private CarSelectBean selectBean;
    private long receiveId;
    private SimpleDateFormat endFormat;
    private SimpleDateFormat format;
    private boolean isToast;
    private boolean needUpdateMileAndDate;
    private X3HomeTimeSelectDialog timeSelectDialog;
    private SimpleDateFormat usEndFormat;
    private int nextMiles;

    private String salutation;

    private String carBrandName,carStyleName,carTypeName,carModelTime,carCurrentMile;

    // 性别
    private String gender = "MALE";

    private List<String> useNameList;
    private List<CarBrandBean> nameList;
    private List<String> sexList;
    private X3SelectSunNameAdapter sunNameAdapter;
    private int selectYear;
    private int selectMoth;
    private X3CarSexAdapter sexAdapter;
    private String moderYear;
    private boolean customSet;
    private String perMiles;
    private TextView tv_total;
    private String km;
    private boolean isSubmit;

    public X3BottomAffirmCarDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        km = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");
        ll_car_brand = getView(R.id.ll_car_brand);
        tv_brand_name_span = getView(R.id.tv_brand_name_span);
        et_car_brand = getView(R.id.et_car_brand);
        iv_brand_icon = getView(R.id.iv_brand_icon);
        nv_view = getView(R.id.nv_view);
        ll_view = getView(R.id.ll_view);
        v_click = getView(R.id.v_click);

        ll_car_pic = getView(R.id.ll_car_pic);
        tv_car_pic_span = getView(R.id.tv_car_pic_span);
        tv_car_pic = getView(R.id.tv_car_pic);
        v_pic = getView(R.id.v_pic);
        lv_car = getView(R.id.lv_car);
        tv_title = getView(R.id.tv_title);

        ll_time = getView(R.id.ll_time);
        tv_car_time_span = getView(R.id.tv_car_time_span);
        et_car_time = getView(R.id.et_car_time);

        ll_mile = getView(R.id.ll_mile);
        tv_miles_span = getView(R.id.tv_miles_span);
        et_miles = getView(R.id.et_miles);

        et_car_name = getView(R.id.et_car_name);

        et_car_vin = getView(R.id.et_car_vin);
        iv_take = getView(R.id.iv_take);
        tv_cancel = getView(R.id.tv_cancel);
        btn_next = getView(R.id.btn_next);

        ll_use_name = getView(R.id.ll_use_name);
        rlv_name = getView(R.id.rlv_name);
        et_car_last_name = getView(R.id.et_car_last_name);
        ll_use = getView(R.id.ll_use);
        rlv_sex = getView(R.id.rlv_sex);
        tv_total = findViewById(R.id.tv_total);

        ll_mile.setOnClickListener(this);
        ll_time.setOnClickListener(this);
        ll_car_brand.setOnClickListener(this);
        ll_car_pic.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        btn_next.setiOnClickAffirm(this);
        iv_take.setOnClickListener(this);
        boolean isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);
        iv_take.setVisibility(isSdk ? View.INVISIBLE : View.VISIBLE);
        ll_use.setOnClickListener(this);
        ll_use_name.setOnClickListener(v -> {

        });
        v_click.setOnClickListener(v -> hideKeyboard(et_car_name.getWindowToken()));


        btn_next.changeBtnStatusButClick(false);

        et_car_vin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkStrEmpty();
                if(X3Constent.isChina()){
                    if(s.toString().trim().length() == 17){
                        vinToCarType(s.toString().trim());
                    }
                }

            }
        });
        et_car_name.addTextChangedListener(this);

        endFormat = new SimpleDateFormat("yyyy-MM",Locale.CHINA);
        usEndFormat = new SimpleDateFormat("MMM, yyyy",Locale.ENGLISH);
        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        img_6 = X3ImgDownload.getImageFromAssetsFile("img_6.png", mContext);

        sexList = new ArrayList<>();
        rlv_sex.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
        int countrySex = X3Constent.getCountrySex();
        switch (countrySex) {
            case 0:
                sexList = new ArrayList<>(Arrays.asList(mContext.getResources().getStringArray(R.array.cn_tw_gender)));
                break;
            case 2:
                sexList = new ArrayList<>(Arrays.asList(mContext.getResources().getStringArray(R.array.de_gender)));
                break;
            default:
                sexList = new ArrayList<>(Arrays.asList(mContext.getResources().getStringArray(R.array.my_uk_us_gender)));
                break;
        }

        sexAdapter = new X3CarSexAdapter(mContext);
        rlv_sex.setAdapter(sexAdapter);
        sexAdapter.setiOnClickSex(this);
        sexAdapter.changeSexAdapter(sexList);

        int whichCountry = X3Constent.getWhichCountry();
        useNameList = new ArrayList<>();
        switch (whichCountry) {
            case 0:
                useNameList = X3StringUtils.getAssetsForUseName(mContext,"first_name/cn_firstName.json");
                break;
            case 1:
                useNameList = X3StringUtils.getAssetsForUseName(mContext,"first_name/tw_firstName.json");
                break;
            case 2:
                useNameList = X3StringUtils.getAssetsForUseName(mContext,"first_name/my_firstName.json");
                break;
            case 3:
                useNameList = X3StringUtils.getAssetsForUseName(mContext,"first_name/uk_firstName.json");
                break;
            case 4:
                useNameList = X3StringUtils.getAssetsForUseName(mContext,"first_name/de_firstName.json");
                break;
            case 5:
                useNameList = X3StringUtils.getAssetsForUseName(mContext,"first_name/us_firstName.json");
                break;
            case 6:
                useNameList = X3StringUtils.getAssetsForUseName(mContext,"first_name/ie_firstName.json");
                break;
        }

        et_car_name.getViewTreeObserver().addOnGlobalLayoutListener(this);

        rlv_name.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
        sunNameAdapter = new X3SelectSunNameAdapter(useNameList,mContext);
        rlv_name.setAdapter(sunNameAdapter);
        sunNameAdapter.setiOnClickSelect(name -> {
            et_car_name.setText(name + "");
            et_car_name.setSelection(name.length());
        });

        nameList = new ArrayList<>();
        if (X3StringUtils.isListEmpty(useNameList)) {
            return;
        }
        for (String name : useNameList) {
            CarBrandBean brandBean = new CarBrandBean();
            brandBean.setLabel(name);
            nameList.add(brandBean);
        }
        et_car_name.setOnFocusChangeListener(this);
        et_car_vin.setOnFocusChangeListener(this);
        et_car_last_name.setOnFocusChangeListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_bottom_affirm_car_dialog;
    }

    /**
     * 读取车辆信息
     */
    public void setCarInfo(long receiveId,boolean needUpdateMileAndDate) {
        this.receiveId = receiveId;
        this.needUpdateMileAndDate = needUpdateMileAndDate;
        showNeedMileUpdate();
        NetWorkHttp.getApi().getReceiveBase(receiveId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<HomeMainCarBean>() {
                    @Override
                    protected void onDone(HomeMainCarBean homeMainCarBean) {
                        setCarDataInfo(homeMainCarBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void showNeedMileUpdate() {
        ll_time.setVisibility(needUpdateMileAndDate ? View.VISIBLE : GONE);
        ll_mile.setVisibility(needUpdateMileAndDate ? View.VISIBLE : GONE);
    }

    private void setCarDataInfo(HomeMainCarBean mainCarBean) {
        if (mainCarBean == null) {
            return;
        }
        carBrandId = mainCarBean.getCarBrandId();
        carStyleId = mainCarBean.getCarStyleId();
        carTypeId = mainCarBean.getCarTypeId();
        carId = mainCarBean.getCarId();
        carNum = mainCarBean.getCarNum();

        tv_title.setText(carNum + "");
        // 是否更新了车型库
        boolean needUpdateCarStyle = mainCarBean.isNeedUpdateCarStyle();
        if (needUpdateCarStyle) {
            X3PointDialog pointDialog = new X3PointDialog( mContext,mainCarBean.getCarNum() + "",
                    mContext.getString(R.string.x3_car_update_brand_and_type),"",mContext.getString(R.string.x3_affirm_info));
            pointDialog.show();
            pointDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                @Override
                public void iBtnAffirmClick() {
                    switchJumpDialog();
                }

                @Override
                public void iBtnCancelClick() {
                    switchJumpDialog();
                    dismiss();
                }
            });

        }else {
            setCarBrand(mainCarBean);
//            switchJumpDialog();
        }

        if (needUpdateCarStyle || carBrandId <= 0) {
            requestCarNumRecognition(mainCarBean.getCarNum());
        }

        String carVin = X3StringUtils.isEmpty(mainCarBean.getCarVin()) ? "" : mainCarBean.getCarVin();
        et_car_vin.setText(carVin);
        if (!X3StringUtils.isEmpty(carVin)) {
            et_car_vin.setSelection(carVin.length());
        }
        moderYear = mainCarBean.getCarProductionDate();
        if (!X3StringUtils.isEmpty(mainCarBean.getCarProductionDate())) {
            et_car_time.setVisibility(View.VISIBLE);
            try {
                String format;
                if (LanguageUtiles.isZhRCN()) {
                    format  = endFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                }else {
                    format = usEndFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                }
                carModelTime = mainCarBean.getCarProductionDate();

                String selectFormat  = endFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                String[] split = selectFormat.split("-");
                if (!X3StringUtils.isEmpty(split[0])) {
                    selectYear = Integer.parseInt(split[0]);
                }
                if (!X3StringUtils.isEmpty(split[1])) {
                    selectMoth = Integer.parseInt(split[1]);
                }

                et_car_time.setText(format);
                et_car_time.setTextColor(Color.parseColor("#333333"));

            } catch (ParseException e) {
                e.printStackTrace();
            }
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv_car_time_span.setTextColor(Color.parseColor("#707380"));
        }else {
            carModelTime = "";
            et_car_time.setVisibility(GONE);
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
            tv_car_time_span.setTextColor(Color.parseColor("#B1B3BD"));
        }

//        String miles = StringUtils.isEmpty(mainCarBean.getEstimateCurrentMiles()) ? "" : mainCarBean.getEstimateCurrentMiles();
//        if (StringUtils.isEmpty(miles)) {
//            et_miles.setText("");
//            carCurrentMile = "";
//            et_miles.setVisibility(GONE);
//            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
//            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
//        }else {
//            et_miles.setVisibility(View.VISIBLE);
//            tv_miles_span.setTextColor(Color.parseColor("#707380"));
//            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
//            nextMiles = (int) Double.parseDouble(miles);
//            et_miles.setText(nextMiles + "");
//            carCurrentMile = nextMiles + "";
//        }
        customSet = mainCarBean.getCustomSet();


        String miles = X3StringUtils.isEmpty(mainCarBean.getEstimateCurrentMiles()) ? "" : mainCarBean.getEstimateCurrentMiles();
        if (X3StringUtils.isEmpty(miles)) {
            tv_total.setText("");
            carCurrentMile = "";
            tv_total.setVisibility(GONE);
            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        }else {
            tv_total.setVisibility(View.VISIBLE);
            tv_miles_span.setTextColor(Color.parseColor("#707380"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            nextMiles = (int) Double.parseDouble(miles);
            tv_total.setText(nextMiles + km);
            carCurrentMile = nextMiles + "";
        }
        perMiles = X3StringUtils.isEmpty(mainCarBean.getPerMiles()) ? "" : mainCarBean.getPerMiles();
        if (X3StringUtils.isEmpty(perMiles)) {
            et_miles.setText("");
            carCurrentMile = "";
            et_miles.setVisibility(GONE);
        }else {
            et_miles.setVisibility(View.VISIBLE);
            int permiles = (int) Double.parseDouble(perMiles);
            et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile)+ " "+permiles +km);
        }

        String lastName = X3StringUtils.isEmpty(mainCarBean.getLastName()) ? "" : mainCarBean.getLastName();
        et_car_name.setText(lastName);

        String firstName = X3StringUtils.isEmpty(mainCarBean.getFirstName()) ? "" : mainCarBean.getFirstName();
        et_car_last_name.setText(firstName);

        String salut= mainCarBean.getSalutation();
        if (!X3StringUtils.isEmpty(salut)) {
            salutation = salut;
            if (sexAdapter != null) {
                sexAdapter.changeSelectSex(salutation);
            }
        }

        gender = mainCarBean.getGender();

        checkStrEmpty();
    }

    private void switchJumpDialog() {
        if (X3StringUtils.isEmpty(et_car_brand.getText().toString())) {
            ll_car_brand.performClick();
            return;
        }
        if (v_pic.getVisibility() == GONE && lv_car.getVisibility() == GONE && tv_car_pic.getVisibility() == GONE) {
            ll_car_pic.performClick();
            return;
        }
    }

    private void requestCarNumRecognition(String carNum) {
        NetWorkHttp.getApi().getCarNumRecognition(carNum)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<CarNumRecognitionBean>() {
                    @Override
                    protected void onDone(CarNumRecognitionBean carNumRecognitionBean) {
                        if (carNumRecognitionBean == null) {
                            return;
                        }
                        String vin = carNumRecognitionBean.getVin();
                        if (!X3StringUtils.isEmpty(vin)) {
                            et_car_vin.setText(vin);
                        }

                        if (carBrandId > 0) {
                            return;
                        }
                        carBrandId = carNumRecognitionBean.getCarBrandId();
                        if (carBrandId <= 0) {
                            return;
                        }

                        String carBrand = X3StringUtils.isEmpty(carNumRecognitionBean.getCarBrandName()) ? "" : carNumRecognitionBean.getCarBrandName();
                        String seriesName = X3StringUtils.isEmpty(carNumRecognitionBean.getCarStyleName()) ? "" : carNumRecognitionBean.getCarStyleName();

                        if (X3StringUtils.isEmpty(seriesName)) {
                            et_car_brand.setText("");
                            et_car_brand.setVisibility(GONE);
                            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                            tv_brand_name_span.setTextColor(Color.parseColor("#B1B3BD"));
                        }else {
                            carBrandName = carBrand;
                            carStyleName = seriesName;
                            carTypeName = carNumRecognitionBean.getCarTypeName();
                            carBrandId = carNumRecognitionBean.getCarBrandId();
                            carStyleId = carNumRecognitionBean.getCarStyleId();
                            carTypeId = carNumRecognitionBean.getCarTypeId();

                            et_car_brand.setTextColor(Color.parseColor("#333333"));
                            et_car_brand.setText(carBrand + " " + seriesName);
                            et_car_brand.setVisibility(View.VISIBLE);
                            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
                            tv_brand_name_span.setTextColor(Color.parseColor("#707380"));

                            if (brandSelectDialog != null) {
                                brandSelectDialog.dismiss();
                            }
                        }

                        String productionDate = carNumRecognitionBean.getProductionDate();
                        if (!X3StringUtils.isEmpty(productionDate)) {
                            et_car_time.setVisibility(View.VISIBLE);

                            try {
                                String format;
                                if (LanguageUtiles.isZhRCN()) {
                                    format  = endFormat.format(X3BottomAffirmCarDialog.this.format.parse(productionDate));
                                }else {
                                    format = usEndFormat.format(X3BottomAffirmCarDialog.this.format.parse(productionDate));
                                }
                                carModelTime = carNumRecognitionBean.getProductionDate();
                                et_car_time.setText(format);
                                et_car_time.setTextColor(Color.parseColor("#333333"));

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
                            tv_car_time_span.setTextColor(Color.parseColor("#707380"));
                        }else {
                            carModelTime = "";
                            et_car_time.setVisibility(GONE);
                            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                            tv_car_time_span.setTextColor(Color.parseColor("#B1B3BD"));
                        }

                        checkStrEmpty();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 赋值车辆品牌车款和缩略图
     * @param mainCarBean
     */
    private void setCarBrand(HomeMainCarBean mainCarBean) {
        String carBrand = X3StringUtils.isEmpty(mainCarBean.getCarBrandName()) ? "" : mainCarBean.getCarBrandName();
        String seriesName = X3StringUtils.isEmpty(mainCarBean.getCarStyleName()) ? "" : mainCarBean.getCarStyleName();

//        iv_brand_icon.setVisibility(StringUtils.isEmpty(mainCarBean.getCarBrandResourceUrl()) ? View.INVISIBLE : View.VISIBLE);
        iv_brand_icon.setVisibility(View.INVISIBLE);
        if (X3StringUtils.isEmpty(seriesName)) {
            et_car_brand.setText("");
            et_car_brand.setVisibility(GONE);
            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
            tv_brand_name_span.setTextColor(Color.parseColor("#B1B3BD"));
        }else {
            et_car_brand.setTextColor(Color.parseColor("#333333"));
            et_car_brand.setText(carBrand + " " + seriesName);
            et_car_brand.setVisibility(View.VISIBLE);
            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv_brand_name_span.setTextColor(Color.parseColor("#707380"));

            carBrandName = carBrand;
            carStyleName = seriesName;
            carTypeName = mainCarBean.getCarTypeName();
            Glide.with(mContext).load(X3StringUtils.getImageUrl(mainCarBean.getCarBrandResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_icon_no).skipMemoryCache(false).dontAnimate()
            ).into(iv_brand_icon);
        }


        this.colorId = mainCarBean.getColorId();
        this.carPicTempletId = mainCarBean.getCarPicTempletId();
        if (colorId != 0 || carPicTempletId != 0) {
            HomeMainCarBean.CarPicTempletEntityBean picBean = mainCarBean.getCarPicTempletEntityBean();
            if (picBean == null) {
                showCarPicSelect(1);
                v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
            }else {
                setCarColor(picBean,mainCarBean.getCarNum());
            }

        }else {
            // 请求是否当前车型是否有车款缩略图
            getCarPicAndColor(carId,carStyleId,false,mainCarBean.getCarNum());
        }

        checkStrEmpty();
    }

    /**
     * 请求车款缩略图和图片
     * @param carId
     * @param carStyleId
     */
    private void getCarPicAndColor(long carId, long carStyleId,boolean isShow,String carNum) {
        HashMap<String,Object> map = new HashMap<>();
        if (carId > 0) {
            map.put("carId",carId);
        }
        map.put("carNum",carNum);
        if (carStyleId > 0) {
            map.put("carStyleId",carStyleId);
        }else {
            showCarPicSelect(0);
            return;
        }

        NetWorkHttp.getApi().showCarPicAndColor(map)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CarPicAndColorBean>>() {
                    @Override
                    protected void onDone(List<CarPicAndColorBean> picAndColorBeans) {
                        mList = picAndColorBeans;

                        if (picAndColorDialog != null) {
                            picAndColorDialog.show();
                            if (isToast) {
                                picAndColorDialog.changeNoToast();
                                isToast = false;
                            }
                            picAndColorDialog.changeSelectColor(colorId,carPicTempletId);
                            picAndColorDialog.sendCarId(carId);
                        }
                        if (X3StringUtils.isListEmpty(mList)) {
                            colorId = 0;
                            carPicTempletId = 0;
                            X3ToastUtils.showMessage(mContext.getString(R.string.x3_car_no_pic));

                            showCarPicSelect(1);
                            v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
                            checkStrEmpty();

                            mList = new ArrayList<>();
                            mList.add(new CarPicAndColorBean());
                            if (picAndColorDialog != null) {
                                picAndColorDialog.changeCarAndPic(mList,carNum,0,0);
                                if (!isShow) {
                                    picAndColorDialog.dismiss();
                                }

                            }
                        }else if (mList.size() == 1) {
                            CarPicAndColorBean carPicAndColorBean = picAndColorBeans.get(0);
                            String carNum1 = carPicAndColorBean.getCarNum();
                            colorId = carPicAndColorBean.getColorId();
                            carPicTempletId = carPicAndColorBean.getCarPicTempletId();

                            if (!X3StringUtils.isEmpty(carNum1)) {

                                colorId = 0;
                                carPicTempletId = 0;
                                showCarPicSelect(1);
                                checkStrEmpty();
                                v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);

                                mList.add(0,new CarPicAndColorBean());
                                if (picAndColorDialog != null) {
                                    picAndColorDialog.changeCarAndPic(mList,carNum,colorId,carPicTempletId);
                                    if (!isShow) {
                                        picAndColorDialog.dismiss();
                                    }
                                }
                            }else {
                                showCarPicSelect(1);
                                checkStrEmpty();

                                HomeMainCarBean.CarPicTempletEntityBean picBean = new HomeMainCarBean.CarPicTempletEntityBean();
                                picBean.setBrakeResourceUrl(carPicAndColorBean.getBrakeResourceUrl());
                                picBean.setColorResourceUrl(carPicAndColorBean.getResourceUrl());
                                picBean.setColorRgbCode(carPicAndColorBean.getColourRgb());
                                picBean.setLightResourceUrl(carPicAndColorBean.getLightResourceUrl());
                                picBean.setMoveJsonResourceUrl(carPicAndColorBean.getMoveJsonResourceUrl());
                                picBean.setType(carPicAndColorBean.getType());
                                picBean.setTyreResourceUrl(carPicAndColorBean.getTyreResourceUrl());

                                setCarColor(picBean,carNum);

                                if (picAndColorDialog != null) {
                                    picAndColorDialog.changeCarAndPic(mList,carNum,colorId,carPicTempletId);
                                }
                            }
                        }else {
                            if (!isShow) {
                                showCarPicSelect(0);
                                return;
                            }
                            XXPermissions.with((Activity) mContext)
                                    .permission(Permission.Group.STORAGE)
                                    .request(
                                            new OnPermissionCallback() {
                                                @Override
                                                public void onGranted(List<String> permissions, boolean all) {
                                                    if(all){
                                                        downCarPicAndColor(mList,carNum);
                                                    }else {
                                                        XXPermissions.startPermissionActivity(mContext);
                                                    }
                                                }
                                            }
//                                            new OnPermission() {
//                                        @Override
//                                        public void hasPermission(List<String> granted, boolean all) {
//
//                                        }
//
//                                        @Override
//                                        public void noPermission(List<String> denied, boolean never) {
//                                            XXPermissions.startApplicationDetails(mContext);
//                                        }
//                                    }

                                    );

                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    private void downCarPicAndColor(List<CarPicAndColorBean> mList,String carNum) {
        allNum = 0;
        cuteNum = 0;
        for (int i = 0; i < mList.size(); i++) {
            String type = mList.get(i).getType();
            String colourRgb = mList.get(i).getColourRgb();
            if ("T_JSON".equals(type)) {

                X3FileUtils.saveBitmap(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images", "img_6.png", img_6);

                // 移动动画
                String moveUrl = mList.get(i).getMoveJsonResourceUrl();
                // 轮胎
                String tyreUrl = X3StringUtils.getImageUrl(mList.get(i).getTyreResourceUrl());
                // 刹车盘
                String brakeUrl = X3StringUtils.getImageUrl(mList.get(i).getBrakeResourceUrl());
                // 亮色车身颜色
                String colorUrl = X3StringUtils.getImageUrl(mList.get(i).getPicUrl());

                if (!X3StringUtils.isEmpty(moveUrl)&& !X3StringUtils.isEmpty(mList.get(i).getTyreResourceUrl())
                        && !X3StringUtils.isEmpty(mList.get(i).getBrakeResourceUrl()) &&
                        !X3StringUtils.isEmpty(mList.get(i).getPicUrl())) {
                    allNum++;
                    downloadDropFile(moveUrl, X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb,false);

                    downCarJsonImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            tyreUrl, "img_2.png",false);

                    downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            colorUrl, "img_4.png",false);

                    downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            brakeUrl, "img_3.png",false);

                    downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            colorUrl, "img_5.png",false);

                }
            }
        }

        if (picAndColorDialog != null) {
            picAndColorDialog.hidePrograssBar();
            picAndColorDialog.changeCarAndPic(mList,carNum,colorId,carPicTempletId);
        }
    }

    private void setCarColor(HomeMainCarBean.CarPicTempletEntityBean picBean, String carNum) {
        String colourRgb = picBean.getColorRgbCode();
        this.picBean = picBean;

        if ("T_JSON".equals(picBean.getType())) {
            showCarPicSelect(2);

            X3FileUtils.saveBitmap(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images", "img_6.png", img_6);

            // 移动动画
            String moveUrl = picBean.getMoveJsonResourceUrl();
            // 轮胎
            String tyreUrl = X3StringUtils.getImageUrl(picBean.getTyreResourceUrl());
            // 刹车盘
            String brakeUrl = X3StringUtils.getImageUrl(picBean.getBrakeResourceUrl());
            // 亮色车身颜色
            String colorUrl = X3StringUtils.getImageUrl(picBean.getColorResourceUrl());

            allNum = 0;
            cuteNum = 0;
            if (!X3StringUtils.isEmpty(moveUrl)&& !X3StringUtils.isEmpty(picBean.getTyreResourceUrl())
                    && !X3StringUtils.isEmpty(picBean.getBrakeResourceUrl()) &&
                    !X3StringUtils.isEmpty(picBean.getColorResourceUrl())) {
                allNum++;

                downloadDropFile(moveUrl, X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb,true);

                downCarJsonImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        tyreUrl, "img_2.png",true);

                downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        colorUrl, "img_4.png",true);

                downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        brakeUrl, "img_3.png",true);

                downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        colorUrl, "img_5.png",true);

            }else {
                lv_car.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
            }
        }else {
            showCarPicSelect(1);
            Glide.with(mContext).load(X3StringUtils.getImageUrl(picBean.getColorResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
            ).into(v_pic);
        }
    }

    /**
     * 下载需要的json
     *
     * @param jsonUrl  掉落json 或者 车辆行驶json
     * @param jsonPath 将josn存储到本地的文件地址
     */
    public void downloadDropFile(String jsonUrl, String jsonPath,boolean isOne) {
        if (!X3StringUtils.isEmpty(jsonUrl)) {
            new OkHttpClient().newCall(new Request.Builder().url(X3StringUtils.getImageUrl(jsonUrl)).build()).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull okhttp3.Call call, @NotNull Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        // 下载成功 但是回调失败
                        downSuccess(isOne);
                        return;
                    } else {
                        ResponseBody body = response.body();
                        String source = body.string();
                        // 存储
                        X3FileUtils.writeIntoSDcard(jsonPath,source , "carMove.json");
                        downSuccess(isOne);
                    }
                }

                @Override
                public void onFailure(@NotNull okhttp3.Call call, @NotNull IOException e) {
                    // 失败了也要回调
                    downSuccess(isOne);
                }
            });
        } else {
            downSuccess(isOne);
        }
    }

    /**
     * 下载需要的图片
     *
     * @param imagePath 存储json所需的图片 Environment.getExternalStorageDirectory().getPath() + "/car/" + 车牌号 + "/images", 颜色 + ".png"
     * @param carUrl    json所需的图片
     */
    public void downCarImageUrl(String imagePath, String carUrl, String imageName,boolean isOne) {
        ThreadPoolManager.getInstance().execute(() -> {
            try {
                X3FileUtils.saveFile(X3FileUtils.getImage(carUrl), imageName, imagePath);
                downImageLightSuccess(isOne);
            } catch (Exception e) {
                e.printStackTrace();
                downImageLightSuccess(isOne);
            }
        });
    }

    public void downImageLightSuccess(boolean isOne) {
        cuteNum++;
        if (mContext == null) {
            return;
        }
        ((Activity)mContext).runOnUiThread(() -> {
            if (isOne) {
                // 已经有数据再次进入下载缩略图
                setOneLottie();
            }else {
                showHomeCarAdapter();
            }
        });
    }

    /**
     * 显示默认缩略图
     */
    private void setOneLottie() {
        showCarPicSelect(2);
        lv_car.setRepeatCount(-1);
        lv_car.setImageAssetDelegate(asset -> {
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + picBean.getColorRgbCode() +
                        "/images/" + asset.getFileName());
                //把流转化为Bitmap图片
                return BitmapFactory.decodeStream(fileInputStream);

            } catch (Exception e) {
                //Log.e("SSSS","获取图片报错："+e.toString());
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        });
        String carMove = X3FileUtils.readBeanFromSdCard(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + picBean.getColorRgbCode() + "/carMove.json");
        LottieTask<LottieComposition> lottieMoveTask = LottieCompositionFactory.fromJsonString(carMove, "move" + picBean.getColorRgbCode());
        lottieMoveTask.addListener(result -> {
            lv_car.setComposition(result);
            lv_car.setProgress(0);
            lv_car.playAnimation();
        });
    }

    /**
     * 下载需要的图片
     *
     * @param imagePath 存储json所需的图片 Environment.getExternalStorageDirectory().getPath() + "/car/" + 车牌号 + "/images", 颜色 + ".png"
     * @param carUrl    json所需的图片
     */
    public void downCarJsonImageUrl(String imagePath, String carUrl, String imageName,boolean isOne) {
        ThreadPoolManager.getInstance().execute(() -> {
            try {
//                Log.e("SSSS","下载图片:"+carUrl);
                X3FileUtils.saveFile(X3FileUtils.getImage(carUrl), imageName, imagePath);
                downImageSuccess(isOne);

            } catch (Exception e) {
                e.printStackTrace();
                downImageSuccess(isOne);
            }
        });
    }

    public void downImageSuccess(boolean isOne) {
        cuteNum++;
        if (mContext == null) {
            return;
        }
        ((Activity)mContext).runOnUiThread(() -> {
            if (isOne) {
                // 已经有数据再次进入下载缩略图
                setOneLottie();
            }else {
                showHomeCarAdapter();
            }
        });
    }


    private void showHomeCarAdapter() {
        if (cuteNum < allNum * 5) {
            return;
        }
        if (picAndColorDialog != null) {
            picAndColorDialog.hidePrograssBar();
            X3BottomHomeCarAndColorAdapter bottomHomeCarAndColorAdapter = picAndColorDialog.getBottomHomeCarAndColorAdapter();
            if (bottomHomeCarAndColorAdapter != null) {
                bottomHomeCarAndColorAdapter.notifyDataSetChanged();
            }
        }
    }

    public void downSuccess(boolean isOne) {
        cuteNum++;

        if (mContext == null) {
            return;
        }
        ((Activity)mContext).runOnUiThread(() -> {
            if (isOne) {
                // 已经有数据再次进入下载缩略图
                setOneLottie();
            }else {
                showHomeCarAdapter();
            }
        });
    }

    /**
     * 设置选中车辆缩略图的状态
     * 0 清空
     * 1 正常选中缩略图 并且是图片
     * 2 正常选中缩略图 并且是json
     * 4 选中切割当中的接口
     * @param status
     */
    public void showCarPicSelect(int status) {
        switch (status) {
            case 0:
                colorId = 0;
                carPicTempletId = 0;
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                tv_car_pic_span.setTextColor(Color.parseColor("#B1B3BD"));
                tv_car_pic.setVisibility(GONE);
                v_pic.setVisibility(GONE);
                lv_car.setVisibility(GONE);
                break;
            case 1:
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                tv_car_pic_span.setTextColor(Color.parseColor("#707380"));
                tv_car_pic.setVisibility(GONE);
                v_pic.setVisibility(View.VISIBLE);
                lv_car.setVisibility(GONE);
                break;
            case 2:
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                tv_car_pic_span.setTextColor(Color.parseColor("#707380"));
                tv_car_pic.setVisibility(GONE);
                v_pic.setVisibility(GONE);
                lv_car.setVisibility(View.VISIBLE);
                break;
            case 3:
                tv_car_pic.setVisibility(View.VISIBLE);
                tv_car_pic.setText(mContext.getString(R.string.x3_car_cut_span_notice));
                tv_car_pic.setTextColor(Color.parseColor("#0077ff"));
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
                tv_car_pic_span.setTextColor(Color.parseColor("#707380"));
                v_pic.setVisibility(GONE);
                lv_car.setVisibility(GONE);
                break;
        }
        checkStrEmpty();
    }

    /**
     * 检查按钮是否可以提交
     */
    private boolean checkStrEmpty() {
        this.isSubmit = false;
        boolean isHavePic = v_pic.getVisibility() == View.VISIBLE || lv_car.getVisibility() == View.VISIBLE || tv_car_pic.getVisibility() == View.VISIBLE;

        boolean isSubmit;
        if (needUpdateMileAndDate) {
            isSubmit = !X3StringUtils.isEmpty(carBrandName)
                    && !X3StringUtils.isEmpty(carStyleName) && isHavePic
                    && !X3StringUtils.isEmpty(et_car_name.getText().toString())&&
                    !X3StringUtils.isEmpty(et_miles.getText().toString())&&
                    !X3StringUtils.isEmpty(et_car_time.getText().toString())&&
                    !X3StringUtils.isEmpty(et_car_vin.getText().toString());
        }else {
            isSubmit = !X3StringUtils.isEmpty(carBrandName)
                    && !X3StringUtils.isEmpty(carStyleName) && isHavePic
                    && !X3StringUtils.isEmpty(et_car_name.getText().toString())
                    && !X3StringUtils.isEmpty(et_car_vin.getText().toString());
        }


        btn_next.changeBtnStatusButClick(isSubmit);
        return isSubmit;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_use) {
            X3HomeNameSelectDialog nameSelectDialog = new X3HomeNameSelectDialog(mContext);
            nameSelectDialog.show();
            nameSelectDialog.changeData(mContext.getString(R.string.x3_owner_name), nameList);
            nameSelectDialog.setiOnClick(brandBean -> {
                et_car_name.setText(brandBean.getLabel() + "");
                et_car_name.setSelection(brandBean.getLabel().length());
            });
        } else if (id == R.id.ll_car_pic) {// 车款缩略图
            if (X3StringUtils.isEmpty(carBrandName) || X3StringUtils.isEmpty(carStyleName)) {
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_car_select_style_ck));
                ll_car_brand.performClick();
                return;
            }

            if (picAndColorDialog == null) {
                picAndColorDialog = new X3BottomHomeCarPicAndColorDialog(mContext);
                picAndColorDialog.setNextCarPic(new X3BottomHomeCarPicAndColorDialog.IOnNextCarPic() {
                    @Override
                    public void iOnNextGetCarPic(CarPicAndColorBean carPicAndColorBean, String carMove, int position) {
                        if (carPicAndColorBean == null) {
                            return;
                        }
                        colorId = carPicAndColorBean.getColorId();
                        carPicTempletId = carPicAndColorBean.getCarPicTempletId();

                        String type = carPicAndColorBean.getType();
                        if ("T_JSON".equals(type)) {
                            if (X3StringUtils.isEmpty(carMove)) {
                                showCarPicSelect(1);
                                v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
                            } else {
                                showCarPicSelect(2);
                                lv_car.setRepeatCount(-1);
                                lv_car.setImageAssetDelegate(asset -> {
                                    FileInputStream fileInputStream = null;
                                    try {
                                        fileInputStream = new FileInputStream(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + carPicAndColorBean.getColourRgb() +
                                                "/images/" + asset.getFileName());
                                        //把流转化为Bitmap图片
                                        return BitmapFactory.decodeStream(fileInputStream);

                                    } catch (Exception e) {
                                        //Log.e("SSSS","获取图片报错："+e.toString());
                                    } finally {
                                        if (fileInputStream != null) {
                                            try {
                                                fileInputStream.close();
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                    return null;
                                });
                                LottieTask<LottieComposition> lottieMoveTask = LottieCompositionFactory.fromJsonString(carMove, "move" + carPicAndColorBean.getColourRgbBak() + carPicAndColorBean.getColourRgb() + position);
                                lottieMoveTask.addListener(result -> {
                                    lv_car.setComposition(result);
                                    lv_car.setProgress(0);
                                    lv_car.playAnimation();
                                });

                            }
                        } else {
                            setColorCarPic(carPicAndColorBean);
                        }

                        checkStrEmpty();
                    }

                    @Override
                    public void iOnNextSelectPic(CarPicAndColorBean carPicAndColorBean) {
                        setColorCarPic(carPicAndColorBean);
                        checkStrEmpty();
                    }
                });
            }
            getCarPicAndColor(carId, carStyleId, true, carNum);
        } else if (id == R.id.ll_car_brand) {//选择车辆品牌
            getCarBrandData();
        } else if (id == R.id.tv_cancel) {
            dismiss();
        } else if (id == R.id.iv_take) {
            if (iOnClick != null) {
                iOnClick.iOnClikCameraVin();
            }
        } else if (id == R.id.ll_mile) {//                String input = et_miles.getText().toString();
//                int inputMile = 0;
//                if (!StringUtils.isEmpty(input)) {
//                    inputMile = (int) Double.parseDouble(input);
//                }

//                BottomMileChangeDialog mileChangeDialog = new BottomMileChangeDialog(mContext);
//                mileChangeDialog.show();
//                mileChangeDialog.showCurrentMiles(inputMile,nextMiles);
//                mileChangeDialog.setiOnGetCurrentMile(miles -> {
//                    et_miles.setVisibility(View.VISIBLE);
//                    et_miles.setText(miles + "");
//                    carCurrentMile = miles + "";
//                    tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
//                    tv_miles_span.setTextColor(Color.parseColor("#666666"));
//                    checkStrEmpty();
//                });

            if (X3StringUtils.isEmpty(carModelTime)) {
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_please_select_car_time));
                ll_time.performClick();
                return;
            }
            X3HomeChangeMileDialog changeMileDialog = new X3HomeChangeMileDialog(mContext);
            changeMileDialog.show();
            changeMileDialog.setOnSaveChangeMiles(this);
            if (X3StringUtils.isEmpty(carCurrentMile)) {
                carCurrentMile = "0";
            }
            changeMileDialog.showTotalAndTime((int) Double.parseDouble(carCurrentMile), moderYear, customSet, perMiles);
        } else if (id == R.id.ll_time) {
            if (timeSelectDialog == null) {
                timeSelectDialog = new X3HomeTimeSelectDialog(mContext);
            }
            timeSelectDialog.show();
            timeSelectDialog.setSelect(selectYear, selectMoth, mContext.getString(R.string.x3_delivery_time));
            timeSelectDialog.setiOnClick(X3BottomAffirmCarDialog.this);
        }
    }

    IOnClickCar iOnClick;

    public void setiOnClick(IOnClickCar iOnClick) {
        this.iOnClick = iOnClick;
    }

    @Override
    public void iOnClickSelect(String year, String month, String zhMonth) {
        boolean zhRCN = LanguageUtiles.isZhRCN();
        if (zhRCN) {
            et_car_time.setText(year + "-" + month);
        }else {
            et_car_time.setText(month + ", " + year);
        }

        selectYear = Integer.parseInt(year);
        selectMoth = Integer.parseInt(zhMonth);

        carModelTime = year + "-" + (selectMoth < 10 ? "0" + selectMoth : selectMoth) + "-01 00:00:00";
        moderYear = carModelTime;
        et_car_time.setVisibility(View.VISIBLE);
        et_car_time.setTextColor(Color.parseColor("#333333"));
        tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
        tv_car_time_span.setTextColor(Color.parseColor("#707380"));
        if(!X3StringUtils.isEmpty(carCurrentMile) && !customSet){
            getNowPerMiles((int) Double.parseDouble(carCurrentMile),moderYear);
        }
        checkStrEmpty();
        if (!X3StringUtils.isEmpty(carCurrentMile)) {
            return;
        }
        ll_mile.performClick();
    }
    public void getNowPerMiles(int totalMile,String modelTime) {//若当前里程和日均有值 选完日期后要重新计算日均里程 customSet =false
        if (!X3StringUtils.isEmpty(modelTime)) {
            int  days = X3DateUtils.getDayTimeAfter(modelTime);
            int newPerMiles = (int) (totalMile / days);
            if (newPerMiles > 1000) {
                newPerMiles = 1000;
            }

            tv_total.setVisibility(View.VISIBLE);
            tv_miles_span.setTextColor(Color.parseColor("#707380"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            nextMiles = totalMile;
            tv_total.setText(nextMiles + km);
            carCurrentMile = nextMiles + "";

            et_miles.setVisibility(View.VISIBLE);
            et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile)+ " "+newPerMiles +km);
            perMiles = newPerMiles+"";
            customSet = false;

        }else {
            tv_total.setText("");
            carCurrentMile = "";
            tv_total.setVisibility(GONE);
            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);

            et_miles.setText("");
            carCurrentMile = "";
            et_miles.setVisibility(GONE);
        }
    }
    @Override
    public void iOnClickSelectSex(String sex) {
        salutation = sex;
        gender = X3StringUtils.getCreateUserSex(sex);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();
        if (id == R.id.et_car_name) {
            if (hasFocus) {
                return;
            }
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            ll_view.setTranslationY(0);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
        } else if (id == R.id.et_car_vin || id == R.id.et_car_last_name) {
            if (!hasFocus) {
                return;
            }
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            ll_view.setTranslationY(0);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
        }
    }

    /**
     * 监听软键盘弹起
     */
    @Override
    public void onGlobalLayout() {
        if (!et_car_name.hasFocus()) {
            ll_view.setTranslationY(0);
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
            return;
        }
        Rect r = new Rect();
        //获取当前界面可视部分
        getWindow().getDecorView().getWindowVisibleDisplayFrame(r) ;
        //获取屏幕的高度
        int screenHeight = getWindow().getDecorView().getRootView().getHeight();
        //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
        int heightDifference = screenHeight - r.bottom;
//        Log.e("SSSS", "Keyboard Size: " + "：：" + screenHeight + "::" + r.bottom + "::" + ScreenUtils.getVirtualBarHeight(mContext));
        showAViewOverKeyBoard(heightDifference);

    }

    private void showAViewOverKeyBoard(int heightDifference) {
        if (heightDifference > 300) {//显示
            ll_use_name.setVisibility(View.VISIBLE);
            v_click.setVisibility(View.VISIBLE);
            ll_use_name.post(() -> {
                if (ll_view.getTranslationY() != -(ll_use_name.getHeight() + X3ScreenUtils.dipToPx(20,mContext))) {
                    ll_view.setTranslationY(-(ll_use_name.getHeight() + X3ScreenUtils.dipToPx(20,mContext)));
                }
            });
        } else {
            //隐藏
            ll_view.setTranslationY(0);
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
        }
    }

    @Override
    public void onSaveChangeMiles(String selectedTotalItemData, String selectedPerItemData, boolean onSaveChangeMiles) {
        et_miles.setVisibility(View.VISIBLE);
        tv_total.setVisibility(View.VISIBLE);
        tv_total.setText(selectedTotalItemData+" "+km);
        et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile)+ " "+selectedPerItemData +km);
        carCurrentMile = selectedTotalItemData;
        perMiles = selectedPerItemData;
        customSet = onSaveChangeMiles;
        System.out.println("是否手动修改" + onSaveChangeMiles);
    }

    public interface IOnClickCar {
        void iOnClikCameraVin();
    }

    /**
     * 获取车辆品牌的数据
     */
    private void getCarBrandData() {

        brandSelectDialog = new X3HomeBrandSelectDialog(mContext);
        brandSelectDialog.show();
        brandSelectDialog.setiOnClick(new X3HomeBrandSelectDialog.IOnClickCar() {
            @Override
            public void iOnClickSelect(CarBrandBean brandBean, boolean isSearchStyle) {
                if (isSearchStyle){
                    CarBrandBean brandBean1 = new CarBrandBean();
                    brandBean1.setLabel(brandBean.getBrandName());
                    brandBean1.setValue(brandBean.getCarBrandId());
                    CarBrandBean brandBean2 = new CarBrandBean();
                    brandBean2.setLabel(brandBean.getStyleName());
                    brandBean2.setValue(brandBean.getCarStyleId());
                    styleSelected(brandBean1,brandBean2);
                } else {
                    getCarYearData(brandBean);
                }

                if (brandSelectDialog != null) {
                    brandSelectDialog.dismiss();
                }
            }
        });
        //获取车辆品牌
        NetWorkHttp.getApi().showCarBrandAndCommonUse()
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<CarBrandAndCommonBean>() {
                    @Override
                    protected void onDone(CarBrandAndCommonBean carBrandBeans) {
                        if (carBrandBeans == null) {
                            X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_no_select));
                            return;
                        }
                        brandBeanList = carBrandBeans.list;
                        if (X3StringUtils.isListEmpty(brandBeanList)) {
                            // 这里是为了防止频繁的打开Dailog出现数组越界的问题
                            X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_no_select));
                            return;
                        } else {
                            if (brandSelectDialog != null) {
                                List<CarModelSelectBean> selectLists = new ArrayList<>();
                                brandSelectDialog.changeData(mContext.getString(R.string.x3_brand),brandBeanList,carBrandBeans.commonList,selectLists);
                            }
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 获取车款
     */
    private void getCarYearData(CarBrandBean brandBean) {
        if (styleSelectDialog == null) {
            styleSelectDialog = new X3HomeStyleSelectDialog(mContext);
        }
        styleSelectDialog.show();
        styleSelectDialog.setiOnClick(data -> {
            if (data == null) {
                return;
            }
            if (mContext.getString(R.string.x3_home_no_select).equals(data.getLabel())) {
                return;
            }
            styleSelected(brandBean,data);
            if (styleSelectDialog != null) {
                styleSelectDialog.dismiss();
            }
        });

        //获取车款
        NetWorkHttp.getApi().receiveShowCarStyle(Integer.parseInt(brandBean.getValue()))
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CarBrandBean>>() {
                    @Override
                    protected void onDone(List<CarBrandBean> carBrandBeans) {
                        carBrandList = carBrandBeans;
                        if (X3StringUtils.isListEmpty(carBrandList)) {
                            //这里是为了防止出现数组越界的BUG
                            carBrandList.add(new CarBrandBean(mContext.getString(R.string.x3_home_no_select),"0"));
                        }
                        if (styleSelectDialog != null) {
                            styleSelectDialog.changeData(mContext.getString(R.string.x3_models) + "",
                                    carBrandList,carStyleName,brandBean.getLabel());
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void styleSelected(CarBrandBean brandBean,CarBrandBean data){
        carBrandName = brandBean.getLabel();
        carBrandId = Long.parseLong(brandBean.getValue());
        carStyleName = data.getLabel();
        if (!X3StringUtils.isEmpty(data.getValue())) {
            carStyleId = Long.parseLong(data.getValue());
        }

        String beforeBrand = et_car_brand.getText().toString();
        if (beforeBrand.equals(carBrandName + " " + carStyleName )) {
            return;
        }

        picAndColorDialog = null;

        carTypeId = 0;

        showCarPicSelect(0);

        setBrandName(brandBean);

        getShowCarTypeData(carStyleId);

        getCarPicAndColor(carId,carStyleId,false,carNum);

    }

    private void setBrandName(CarBrandBean brandBean) {
        CarBrandBean.KwParamBean kwParam = brandBean.getKwParam();
//        iv_brand_icon.setVisibility(View.VISIBLE);
        iv_brand_icon.setVisibility(View.INVISIBLE);
        if (kwParam != null){
            Glide.with(mContext).load(X3StringUtils.getImageUrl(kwParam.getResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_icon_no).skipMemoryCache(false).dontAnimate()
            ).into(iv_brand_icon);
        }

        tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
        tv_brand_name_span.setTextColor(Color.parseColor("#707380"));
        et_car_brand.setVisibility(View.VISIBLE);
        et_car_brand.setTextColor(Color.parseColor("#333333"));
        et_car_brand.setText(carBrandName + " " + carStyleName);
    }

    private void getShowCarTypeData(long carStyleId) {
        //获取车辆车型
        NetWorkHttp.getApi().receiveShowCarType(carStyleId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CarNewTypeBean>>() {
                    @Override
                    protected void onDone(List<CarNewTypeBean> carBrandBeans) {
                        if (!X3StringUtils.isListEmpty(carBrandBeans)) {
                            carTypeName = carBrandBeans.get(0).type;
                            carTypeId = carBrandBeans.get(0).id;
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void setColorCarPic(CarPicAndColorBean carPicAndColorBean) {
        showCarPicSelect(1);
        String resourceUrl = carPicAndColorBean.getResourceUrl();
        if (X3StringUtils.isEmpty(resourceUrl)) {
            v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
            checkStrEmpty();
            return;
        }
        if (resourceUrl.startsWith("/")) {
            // 这是切割过程中选择了
            waitingForCarPicTemplet = true;
            showCarPicSelect(3);
        }else {
            Glide.with(mContext).load(X3StringUtils.getImageUrl(carPicAndColorBean.getResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
            ).into(v_pic);
        }
        checkStrEmpty();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        checkStrEmpty();

        String containName = et_car_name.getText().toString();
        if (X3StringUtils.isEmpty(containName)) {
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
            return;
        }
        List<String> afterNameList = new ArrayList<>();
        for (String name : useNameList) {
            String s1 = name.toLowerCase();
            if (!s1.contains(containName.toLowerCase())) {
                continue;
            }
            afterNameList.add(name);
        }
        if (sunNameAdapter != null) {
            sunNameAdapter.refreshSunName(afterNameList);
        }
    }

    public void resetButtonRest() {
        btn_next.reset();
    }

    @Override
    public void iOnClickAffirm() {
        if(!X3Utils.isFastClick() || isSubmit){
            return;
        }
        //下一步
        if (X3StringUtils.isEmpty(carBrandName) || X3StringUtils.isEmpty(carStyleName)) {
            et_car_brand.setVisibility(View.VISIBLE);
            et_car_brand.setTextColor(Color.parseColor("#F64444"));
            et_car_brand.setText(mContext.getString(R.string.x3_please_select_model));
            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv_brand_name_span.setTextColor(Color.parseColor("#707380"));
        }

        if (tv_car_pic.getVisibility() == GONE && v_pic.getVisibility() == GONE && lv_car.getVisibility() == GONE) {
            tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv_car_pic_span.setTextColor(Color.parseColor("#707380"));
            tv_car_pic.setVisibility(View.VISIBLE);
            tv_car_pic.setTextColor(Color.parseColor("#F64444"));
            tv_car_pic.setText(mContext.getString(R.string.x3_please_select_car_pic));
        }

        if (X3StringUtils.isEmpty(carModelTime)) {
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv_car_time_span.setTextColor(Color.parseColor("#707380"));
            et_car_time.setVisibility(View.VISIBLE);
            et_car_time.setTextColor(Color.parseColor("#F64444"));
            et_car_time.setText(mContext.getString(R.string.x3_please_select_car_time));
        }

        if (!checkStrEmpty()) {
            resetButtonRest();
            return;
        }
        btn_next.showLoading();
        isSubmit = true;

        selectBean = new CarSelectBean();
        selectBean.setId(receiveId);
        selectBean.setCarPicTempletId(carPicTempletId);
        selectBean.setCarBrand(carBrandName);
        selectBean.setCarYear(carStyleName);
        selectBean.setCarStyleName(carTypeName);
        selectBean.setVin(et_car_vin.getText().toString() + "");
        selectBean.setCarProductionDate(carModelTime);
        selectBean.setCarMiles(carCurrentMile);
        selectBean.setLastName(et_car_name.getText().toString() + "");
        selectBean.setFirstName(et_car_last_name.getText().toString() + "");
        selectBean.setWaitingForCarPicTemplet(waitingForCarPicTemplet);
        selectBean.setGender(gender);
        selectBean.setSalutation(salutation);
        selectBean.setPerMiles(perMiles);
        selectBean.setCustomSet(customSet);
        selectBean.setCarOwnerName(et_car_name.getText().toString());
        //设置手机号，暂时不需要手机号
        //selectBean.setMobile(et_car_mobile.getText().toString());
        //设置车辆颜色
        if (colorId != 0) {
            selectBean.setColorId(colorId);
        }
        //车型ID
        if (carTypeId != 0) {
            selectBean.setCarTypeId(carTypeId);
        }
        //品牌ID
        if (carBrandId != 0) {
            selectBean.setCarBrandId(carBrandId);
        }
        //年款ID
        if (carStyleId != 0) {
            selectBean.setCarStyleId(carStyleId);
        }

        updateCarReceive(selectBean);
    }

    private void updateCarReceive(CarSelectBean carSelectBean) {
        UpdateReceiveCarBean carBean = new UpdateReceiveCarBean();
        //参数 车型
        if (!X3StringUtils.isEmpty(carSelectBean.getCarStyleName())) {
            carBean.setCarSeriesId(carSelectBean.getCarTypeId());
            String carStyleName = carSelectBean.getCarStyleName();
            String[] split = carStyleName.split("\\(");
            carBean.setCarSeriesName(split[0]);
        }
        //参数 车辆品牌
        if (!X3StringUtils.isEmpty(carSelectBean.getCarBrand())) {
            carBean.setCarBrandId(carSelectBean.getCarBrandId());
            carBean.setCarBrandName(carSelectBean.getCarBrand());
        }
        //参数年款
        if (!X3StringUtils.isEmpty(carSelectBean.getCarYear())) {
            carBean.setCarStyleId(carSelectBean.getCarStyleId());
            carBean.setCarStyleName(carSelectBean.getCarYear());
        }
        carBean.setCarVin(carSelectBean.getVin() + "");

        carBean.setColorId(carSelectBean.getColorId());

        carBean.setCarPicTempletId(carSelectBean.getCarPicTempletId());

        if (!X3StringUtils.isEmpty(carSelectBean.getCarMiles())) {
            carBean.setEstimateCurrentMiles(carSelectBean.getCarMiles());
        }

        carBean.setCarProductionDate(carSelectBean.getCarProductionDate());

        carBean.setWaitingForCarPicTemplet(carSelectBean.isWaitingForCarPicTemplet());

        if (!X3StringUtils.isEmpty(carNum)) {
            carBean.setCarNum(carNum);
        }

        if (!X3StringUtils.isEmpty(carSelectBean.getCarOwnerName())) {
            carBean.setCarOwnerName(carSelectBean.getCarOwnerName());
        }
        if (!X3StringUtils.isEmpty(carSelectBean.getGender())) {
            carBean.setGender(carSelectBean.getGender());
        }

        if (!X3StringUtils.isEmpty(carSelectBean.getMobile())) {
            carBean.setMobile(carSelectBean.getMobile());
        }

        if (carSelectBean.getCarTypeId() != 0) {
            carBean.setCarTypeId(carSelectBean.getCarTypeId());
        }
        if (!X3StringUtils.isEmpty(carSelectBean.getLastName())) {
            carBean.setLastName(carSelectBean.getLastName());
        }
        if (!X3StringUtils.isEmpty(carSelectBean.getFirstName())) {
            carBean.setFirstName(carSelectBean.getFirstName());
        }

        carBean.setChatroomBaseIdList(new ArrayList<>());

        carBean.setSalutation(carSelectBean.getSalutation());

        carBean.setId(carSelectBean.getId());

        Map<String,Object> map = new HashMap<>();
        if (needUpdateMileAndDate) {
            try {
                Date date = X3TimeUtils.stringToDate(carModelTime, "yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String afterTime = simpleDateFormat.format(date);
                map.put("productDate",afterTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

//            double currentMiles = Double.parseDouble(et_miles.getText().toString());
            map.put("currentMiles",carCurrentMile);
            carBean.setEstimateCurrentMiles(carCurrentMile + "");
        }
        carBean.setCustomSet(customSet);


        if (iOnUpdate != null) {
            iOnUpdate.iOnUpdateReceiveCar(carBean,map);
        }
    }

    IOnUpdate iOnUpdate;

    public void setiOnUpdate(IOnUpdate iOnUpdate) {
        this.iOnUpdate = iOnUpdate;
    }

    public interface IOnUpdate {
        void iOnUpdateReceiveCar(UpdateReceiveCarBean carBean,Map<String,Object> map);
    }

    /**
     * 上传最后一张车辆切割图
     * @param path
     */
    public void changeLastCarCut(String path) {
        colorId = -1;
        carPicTempletId = -1;
        if (picAndColorDialog != null) {
            picAndColorDialog.changeCarCutImage(path);
        }
    }

    /**
     * 获取当前缩略图的选中状态
     * @return
     */
    private int getCarPicStatus() {
        if (v_pic.getVisibility() == GONE && lv_car.getVisibility() == GONE && tv_car_pic.getVisibility() == GONE) {
            return 0;
        }else if (v_pic.getVisibility() == View.VISIBLE) {
            return 1;
        }else if (lv_car.getVisibility() == View.VISIBLE) {
            return 2;
        }
        return 3;
    }

    public void uploadCarCutSuccess(CarPicAndColorBean colorBean) {
        if (picAndColorDialog != null) {
            picAndColorDialog.changeLastCarAndPic(colorBean);
        }else {
            X3ToastUtils.showMessage(mContext.getString(R.string.x3_car_cut_success));
        }
        int carPicStatus = getCarPicStatus();
        if (carPicStatus != 3) {
            return;
        }
        if (colorBean == null) {
            return;
        }
        this.colorId = colorBean.getColorId();
        this.carPicTempletId = colorBean.getCarPicTempletId();
        waitingForCarPicTemplet = false;
        showCarPicSelect(1);

        Glide.with(mContext).load(X3StringUtils.getImageUrl(colorBean.getResourceUrl())).apply(
                new RequestOptions().skipMemoryCache(false).dontAnimate()
        ).into(new ImageViewTarget<Drawable>(v_pic) {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                super.onResourceReady(resource, transition);
                if (picAndColorDialog == null || !picAndColorDialog.isShowing()) {
                    X3ToastUtils.showMessage(mContext.getString(R.string.x3_car_cut_success));
                    isToast = true;
                }
                v_pic.setImageDrawable(resource);
            }

            @Override
            protected void setResource(@Nullable Drawable resource) {

            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
            }
        });

    }

    public void setVin(String vin) {
        if (X3StringUtils.isEmpty(vin)) {
            X3ToastUtils.showMessage("" + mContext.getString(R.string.x3_no_recognize_vin));
            return;
        }
        et_car_vin.setText(vin);
        et_car_vin.setSelection(vin.length());
        checkStrEmpty();
    }


    public void resetEtCarName() {
        ll_use_name.setVisibility(GONE);
        v_click.setVisibility(GONE);
        ll_view.setTranslationY(0);
    }
    /**
     * 根据vin获取品牌数据
     */
    private void vinToCarType(String vin) {
        //获取车辆车型
        NetWorkHttp.getApi().vinToCarType(vin)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<VinResultBean>() {
                    @Override
                    protected void onDone(VinResultBean vinResultBean) {
                        if(vinResultBean == null){
                            switchJumpDialog();
                            return;
                        }
                        if(vinResultBean != null && vinResultBean.carBrandId == null){
                            switchJumpDialog();
                            return;
                        }
                        et_car_brand.setVisibility(View.VISIBLE);
                        et_car_brand.setTextColor(Color.parseColor("#333333"));
                        et_car_brand.setText(vinResultBean.carBrandName+ " " + vinResultBean.carStyleName);
                        et_car_brand.setVisibility(View.VISIBLE);
                        tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                        tv_brand_name_span.setTextColor(Color.parseColor("#707380"));
                        carBrandId = vinResultBean.carBrandId;
                        v_pic.setVisibility(GONE);//缩略图
                        carBrandName = vinResultBean.carBrandName;
                        carStyleName = vinResultBean.carStyleName;
                        carTypeName = vinResultBean.carTypeName;
                        carStyleId = vinResultBean.carStyleId;
                        et_car_time.setText(vinResultBean.producedYear+"");
                        ll_car_pic.performClick();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("检测单详情车型与客户信息弹窗");
    }

    @Override
    public void dismiss() {
        super.dismiss();
        MobclickAgent.onPageEnd("检测单详情车型与客户信息弹窗");
    }
}
